package com.md.mymusic

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.md.album.db.SelfAlbumManager
import com.md.album.utils.AlbumUtil
import com.md.basedpc.constant.BaseConstant
import com.md.datastore.MysaveAlbumManager
import com.md.livingwidget.dialog.PHDialogBackLinstenerImpl
import com.md.livingwidget.dialog.PHDialogUtils
import com.md.mymusic.adapter.CreateAlbumAdapter
import com.md.mymusic.databinding.FragmentMyBuildBinding
import com.md.mymusic.impl.NotifyServiceImpl
import com.md.network.api.Album
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * @author liyue
 * created 2021/2/21
 * desc 自建专辑与收藏专辑Fragment
 */

class AlbumFragment : Fragment() {
    private lateinit var binding: FragmentMyBuildBinding
    private lateinit var ivCreateAlbum: ImageView
    private lateinit var recMyAlbum: RecyclerView
    private lateinit var cltEmptyAlbum: ConstraintLayout
    private var selfCreteAlbumAdapter: CreateAlbumAdapter? = null

    //是否我我创建的专辑
    private var isMine = true

    companion object {
        fun getInstance(isMine: Boolean): AlbumFragment {
            val fragment = AlbumFragment()
            val bundle = Bundle()
            fragment.arguments = bundle
            fragment.isMine = isMine
            return fragment
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        binding = FragmentMyBuildBinding.inflate(LayoutInflater.from(activity))
        ARouter.getInstance().inject(this)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        EventBus.getDefault().register(this)
        initView()
        showSelfCreateAlbum(null)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        EventBus.getDefault().unregister(this)
    }


    private fun initView() {
        binding.fltBuildAlbum.visibility = if (isMine) View.VISIBLE else View.GONE
        var resDrawable = if (isMine) resources.getDrawable(R.drawable.mine_empty_album) else resources.getDrawable(R.drawable.mine_empty_restore)
        binding.ivEmptyAlbum.setImageDrawable(resDrawable)
        var tip = if (isMine) resources.getString(R.string.mine_no_album) else resources.getString(R.string.mine_no_restore)
        binding.tvEmptyAlbum.text = tip
        ivCreateAlbum = binding.ivPlusAlbum
        ivCreateAlbum.setOnClickListener {
            showDialog()
        }
        selfCreteAlbumAdapter = CreateAlbumAdapter(activity!!, isMine, ArrayList())
        recMyAlbum = binding.recMyAlbum
        recMyAlbum.apply {
            layoutManager = LinearLayoutManager(activity)
            adapter = selfCreteAlbumAdapter

        }
        cltEmptyAlbum = binding.cltEmptyAlbum

        binding.ivAlbumMore.setOnClickListener {
            if (isMine) {
                ARouter.getInstance().build("/selfcreateorsave/album").withInt(BaseConstant.ALBUM_TYPE, BaseConstant.SELF_CREATE_ALBUM).navigation()
            } else {
                ARouter.getInstance().build("/selfcreateorsave/album").withInt(BaseConstant.ALBUM_TYPE, BaseConstant.SAVE_ALBUM).navigation()
            }
        }
    }

    private fun showDialog() {
        PHDialogUtils.showEdit(activity, null, "新建专辑", object : PHDialogBackLinstenerImpl() {
            override fun leftBtn(res: String?) {
                createAlbum(res.toString().trim())
            }

            override fun rightBtn(res: String?) {
            }
        },100, true, "")
    }

    private fun createAlbum(title: String) {
        if (TextUtils.isEmpty(title)) {
            Toast.makeText(activity, resources.getString(R.string.mine_notempty_title), Toast.LENGTH_SHORT).show()
            return
        }
        var albumId = AlbumUtil.getAlbumId()
        var album = Album(ArrayList(), "", "", "", albumId.toString(), 0, title,null)
        var isSuc = SelfAlbumManager.getIns().saveAlbum(album)
        if (isSuc) {
            showSelfCreateAlbum(null)
            var bundle = Bundle()
            bundle.putString("SELF_CREATE_TITLE", title)
            ARouter.getInstance()
                    .build("/selfcreate/album")
                    .withString("SELF_CREATE_TITLE", title)
                    .withInt("CREATED_ALBUM_ID", albumId)
                    .navigation()
        } else {
            var tip = resources.getString(R.string.mine_fail_create_album)
            Toast.makeText(activity, tip, Toast.LENGTH_SHORT).show()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun selfAlbumUpdateSuc(model: NotifyServiceImpl.NotifyServiceModel) {
        showSelfCreateAlbum(model)
    }

    private fun showSelfCreateAlbum(model: NotifyServiceImpl.NotifyServiceModel?) {
        var wrapperAlbums = getSelfAlbumData(model)
        wrapperAlbums?.let {
            if (it.isNotEmpty()) {
                recMyAlbum.visibility = View.VISIBLE
                cltEmptyAlbum.visibility = View.GONE
                selfCreteAlbumAdapter?.setData(wrapperAlbums)
            } else {
                recMyAlbum.visibility = View.GONE
                cltEmptyAlbum.visibility = View.VISIBLE
            }
        }
    }

    private fun getSelfAlbumData(model: NotifyServiceImpl.NotifyServiceModel?): List<WrapperAlbum> {
        var albumList = if (isMine) SelfAlbumManager.getIns().allSelfAlbum else MysaveAlbumManager.getIns().allSaveAlbum
        var res = ArrayList<WrapperAlbum>()
        if (albumList.size > 0) {
            for (item in albumList) {
                if (isMine) {
                    var audioList = SelfAlbumManager.getIns().getAudiosByAlbumId(item.id)
                    audioList?.let {
                        res.add(WrapperAlbum(item, audioList.size))
                    }
                } else {
                    var db = MysaveAlbumManager.getIns().getAlbumDBById(item.id)
                    var num = db?.audioNum?.toInt() ?: 0
                    res.add(WrapperAlbum(item, num))
                }
            }
        }
        return res

    }

}